from flask import Blueprint, render_template, g, request, redirect, url_for, flash, jsonify, current_app, abort
from decorators import  login_required
from . import news
from .forms import QuestionForm,AnswerForm
from models import QuestionModel, AnswerModel, News
from exts import db
from sqlalchemy import or_
from response_code import RET

bp = Blueprint("data",__name__,url_prefix="/data")




# 首页新闻列表
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据


@bp.route('/newslist')
@login_required
def newslist():
    """
    1. 获取参数
    2. 参数类型转换
    3. 分页查询
    4. 获取到分页对象中的属性,总页数,当前页,当前页的对象列表
    5. 将对象列表转成字典列表
    6. 携带数据,返回响应
    :return:
    """
    # 1. 获取参数
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","10")

    # 2. 参数类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10

    # 3. 分页查询
    try:
        """
        #判断新闻的分类是否为1
        if cid == "1":
            paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page,per_page,False)
        else:
            paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,per_page,False)
        """

        """
        # 改装,判断新闻的分类是否为1
        filters = ""
        if cid != "1":
            filters = (News.category_id == cid)
        paginate = News.query.filter(filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        """



        paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    # 4. 获取到分页对象中的属性,总页数,当前页,当前页的对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items


    # 5. 将对象列表转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    # 6. 携带数据,返回响应
    return jsonify(errno=RET.OK,errmsg="获取新闻成功",totalPage=totalPage,currentPage=currentPage,newsList=news_list)








@bp.route("/database",methods=['POST', 'GET'])
@login_required
def get_database():

        # 查询热门新闻，根据点击量，查询前十条新闻
        try:
                news = News.query.order_by(News.clicks.desc()).limit(10).all()
        except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

        # 4.将新闻对象列表转成,字典列表
        news_list = []
        for item in news:
            news_list.append(item.to_dict())

        data = {

                "news_list": news_list,
        }

        return render_template("database.html",data=data)


@bp.route("/search",methods=['POST','GET'])
def search():

    # /search?q=xxx
    q = request.form.get("q")
    # filter_by: 直接使用字段的名称
    # filter:使用模型.字段名称
    news = News.query.filter(or_(News.title.contains(q),News.content.contains(q))).order_by(db.text("-create_time"))
    news_list = []
    for item in news:
        news_list.append(item.to_dict())

    data = {

        "news_list": news_list,
    }

    # 6. 携带数据,返回响应
    return render_template("database_detail.html",data=data)



